﻿using MKAdmin.Injection;
using MKAdmin.ToolKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Net.Http;
using System.Text;
using System.Web.Security;
using Newtonsoft.Json;
using System.Net;
using System.Web.Http;
using MKAdmin.Web.Filters;

namespace MKAdmin.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            IOCFactory.Register();

            //GlobalConfiguration.Configuration.Filters.Add(new ApiErrorHandler());
        }

        /// <summary>
        /// 应用程序异常捕获
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e)
        {
            //获取到HttpUnhandledException异常，这个异常包含一个实际出现的异常
            Exception ex = Server.GetLastError();
            //实际发生的异常
            Exception iex = ex.InnerException;

            string errorMsg = String.Empty;
            string particular = String.Empty;
            if (iex != null)
            {
                errorMsg = iex.Message;
                particular = iex.StackTrace;
            }
            else
            {
                errorMsg = ex.Message;
                particular = ex.StackTrace;
            }
            //写入错误日志
            LogHelper.Error(errorMsg + particular);
            Server.ClearError();//处理完及时清理异常

            //发送邮件
            EmailHelper.Send(new EmailHelper.MailInfo()
            {
                Async = false,
                Body = errorMsg,
                Subject = "网站访问异常",
                To = new List<string>() { "mikexu.it@gmail.com" },
                IsBodyHtml = true
            });

            //跳转到错误页面
            HttpContext.Current.Response.Redirect("~/excep/404.html");
        }

    }
}
